package com.jotta.client.dataaccess;

import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
	public static final String KEY_ROWID = "_id";
	public static final String KEY_FILE_PATH = "path";
	public static final String KEY_FILE_REVISION = "revision";
	public static final String KEY_FILE_SIZE = "size";
	public static final String KEY_NUM_OF_ACTIVE = "num_of_active";
	public static final String KEY_DOWNLOADED_DATE = "downloaded_date";
	private static final String TAG = "DBAdapter";

	private static final String DATABASE_NAME = "jotta";
	private static final String DATABASE_TABLE = "file";
	private static final int DATABASE_VERSION = 1;

	private static final String DATABASE_CREATE = "create table "
			+ DATABASE_TABLE + " (" + KEY_ROWID
			+ " integer primary key autoincrement, " + KEY_FILE_PATH
			+ " text not null, " + KEY_FILE_REVISION + " integer not null, "
			+ KEY_FILE_SIZE + " integer not null," + KEY_NUM_OF_ACTIVE
			+ " integer not null," + KEY_DOWNLOADED_DATE
			+ " integer not null);";

	public static final int ROW_ID_COLUMN_INDEX = 0;
	public static final int FILE_PATH_COLUMN_INDEX = 1;
	public static final int FILE_REVISION_COLUMN_INDEX = 2;
	public static final int FILE_SIZE_COLUMN_INDEX = 3;
	public static final int NUM_OF_ACTIVE_COLUMN_INDEX = 4;
	public static final int DOWNLOADED_DATE_COLUMN_INDEX = 5;

	private final Context context;

	private DatabaseHelper DBHelper;
	private SQLiteDatabase db;

	public DBAdapter(Context ctx) {
		this.context = ctx;
		DBHelper = new DatabaseHelper(context);
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			//Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
			//		+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			onCreate(db);
		}
	}

	/**
	 * Open database connection
	 * 
	 * @return
	 * @throws SQLException
	 */
	public DBAdapter open() throws SQLException {
		db = DBHelper.getWritableDatabase();
		return this;
	}

	/**
	 * Close database connection
	 */
	public void close() {
		DBHelper.close();
	}

	/**
	 * Insert file information in database
	 * 
	 * @param path
	 * @param revision
	 * @param size
	 * @param numOfActive
	 * @param downloadedDate
	 * @return
	 */
	public long insertFile(String path, int revision, long size,
			int numOfActive, Date downloadedDate) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_FILE_PATH, path);
		initialValues.put(KEY_FILE_REVISION, revision);
		initialValues.put(KEY_FILE_SIZE, size);
		initialValues.put(KEY_NUM_OF_ACTIVE, numOfActive);
		initialValues.put(KEY_DOWNLOADED_DATE, downloadedDate.toString());
		return db.insert(DATABASE_TABLE, null, initialValues);
	}

	/**
	 * Delete file by row id
	 * 
	 * @param rowId
	 * @return
	 */
	public boolean deleteFileById(long rowId) {
		return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	/**
	 * Delete files by path name
	 * 
	 * @param pathName
	 *            : path name of file
	 * @return
	 */
	public boolean deleteFileByPathName(String pathName) {
		return db.delete(DATABASE_TABLE, KEY_FILE_PATH + "= \"" + pathName
				+ "\"", null) > 0;
	}

	/**
	 * Retrive file information by path name
	 * 
	 * @param pathName
	 * @return
	 */
	public Cursor getFilesByName(String pathName) {
		Cursor mCursor = db.query(DATABASE_TABLE, new String[] { KEY_ROWID,
				KEY_FILE_PATH, KEY_FILE_REVISION, KEY_FILE_SIZE,
				KEY_NUM_OF_ACTIVE, KEY_DOWNLOADED_DATE }, KEY_FILE_PATH
				+ "= \"" + pathName + "\"", null, null, null, KEY_FILE_REVISION
				+ " DESC", null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	/**
	 * Retrive file information by path name
	 * 
	 * @param pathName
	 * @return
	 */
	public Cursor getFileByRow(long rowId) throws SQLException {
		Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
				KEY_ROWID, KEY_FILE_PATH, KEY_FILE_REVISION, KEY_FILE_SIZE,
				KEY_NUM_OF_ACTIVE, KEY_DOWNLOADED_DATE }, KEY_ROWID + "="
				+ rowId, null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	/**
	 * Get file used for auto delete
	 * 
	 * @param numberOfRow
	 *            : number of first row will be used to delete
	 * @return
	 * @throws SQLException
	 */
	public Cursor getRecentFilesForAutoDelete(int numberOfRow)
			throws SQLException {
		String whereClause = KEY_FILE_PATH + " LIKE \""
				+ DataAccess.getInstance().getHomeFolder().getAbsolutePath()
				+ "%\"";
		
		Cursor mCursor =  db.query(true, DATABASE_TABLE, new String[] { KEY_ROWID,
				KEY_FILE_PATH, KEY_FILE_REVISION, KEY_FILE_SIZE,
				KEY_NUM_OF_ACTIVE, KEY_DOWNLOADED_DATE }, whereClause, null,
				null, null, KEY_NUM_OF_ACTIVE + " ASC," + KEY_DOWNLOADED_DATE
						+ " ASC", Integer.toString(numberOfRow));
		
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	/**
	 * Update number of active file info
	 * 
	 * @param rowId
	 * @param numOfActive
	 * @return
	 */
	public boolean updateNumberOfActiveFileInfo(long rowId, int numOfActive) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_NUM_OF_ACTIVE, numOfActive);
		return db.update(DATABASE_TABLE, initialValues,
				KEY_ROWID + "=" + rowId, null) > 0;
	}

}
